<template>
  <view>
    <picker mode="multiSelector" :value="multiIndex" :range="multiRange" @change="onMultiChange" :disabled="disabled">
      <view class="picker-input">
        <text class="picker-text" :class="{ 'placeholder': !props.modelValue }">
          {{ props.modelValue ? formattedDateTime : '请选择' }}
        </text>
        <text class="picker-arrow" v-if="!disabled">></text>
      </view>
    </picker>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  defaultTime: {
    type: String,
    default: () => {
      const now = new Date();
      return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:00`;
    }
  },
  mode: {
    type: String,
    default: 'datetime', // 'datetime', 'date', or 'hour'
    validator: (value) => ['datetime', 'date', 'hour'].includes(value)
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue'])

// 获取星期几的中文表示
const getWeekDay = (date) => {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return weekDays[date.getDay()];
}

// 生成日期范围数据（最近三年）
const getDateRange = () => {
  const dateRange = [];
  const today = new Date();
  const currentYear = today.getFullYear();
  
  // 生成从当前年份到未来两年的所有日期
  for (let year = currentYear; year <= currentYear + 2; year++) {
    for (let month = 1; month <= 12; month++) {
      // 获取当月的天数
      const daysInMonth = new Date(year, month, 0).getDate();
      
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month - 1, day);
        const weekDay = getWeekDay(date);
        
        // 如果年份与今年相同，则不显示年份
        let dateStr;
        if (year === currentYear) {
          dateStr = `${month}月${day}日${weekDay}`;
        } else {
          dateStr = `${year}年${month}月${day}日${weekDay}`;
        }
        
        dateRange.push(dateStr);
      }
    }
  }
  
  return dateRange;
}

// 生成小时范围
const getHourRange = () => {
  const hourRange = [];
  for (let i = 0; i <= 23; i++) {
    hourRange.push(String(i).padStart(2, '0') + '时');
  }
  return hourRange;
}

// 生成分钟范围
const getMinuteRange = () => {
  const minuteRange = [];
  for (let i = 0; i <= 59; i++) {
    minuteRange.push(String(i).padStart(2, '0') + '分');
  }
  return minuteRange;
}

// 生成完整的时间范围数据
const getMultiRange = () => {
  const ranges = [getDateRange()]; // 日期（包含星期）
  
  // 如果是datetime模式，添加小时和分钟
  if (props.mode === 'datetime') {
    ranges.push(getHourRange());    // 小时
    ranges.push(getMinuteRange());  // 分钟
  }
  
  // 如果是hour模式，只添加小时
  if (props.mode === 'hour') {
    ranges.push(getHourRange());    // 小时
  }
  
  return ranges;
}

// 响应式数据
const now = new Date();
const multiRange = ref(getMultiRange());

// 找到今天在日期列表中的索引
const findTodayIndex = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1;
  const day = today.getDate();
  const weekDay = getWeekDay(today);
  const currentYear = new Date().getFullYear();
  
  // 如果是今年，不显示年份
  let todayStr;
  if (year === currentYear) {
    todayStr = `${month}月${day}日${weekDay}`;
  } else {
    todayStr = `${year}年${month}月${day}日${weekDay}`;
  }
  
  const dateRange = multiRange.value[0];
  return dateRange.findIndex(dateStr => dateStr === todayStr);
}

const getInitialMultiIndex = () => {
  const indices = [findTodayIndex() >= 0 ? findTodayIndex() : 0];
  
  // 如果是datetime模式，添加小时和分钟索引
  if (props.mode === 'datetime') {
    indices.push(now.getHours());
    indices.push(now.getMinutes());
  }
  
  // 如果是hour模式，只添加小时索引
  if (props.mode === 'hour') {
    indices.push(now.getHours());
  }
  
  return indices;
};

const multiIndex = ref(getInitialMultiIndex());

// 计算属性
const formattedDateTime = computed(() => {
  if (!multiRange.value.length) return '';
  
  const dateStr = multiRange.value[0][multiIndex.value[0]];
  
  if (props.mode === 'date') {
    return dateStr;
  }
  
  if (props.mode === 'hour') {
    const hour = multiRange.value[1][multiIndex.value[1]];
    return `${dateStr} ${hour}`;
  }
  
  const hour = multiRange.value[1][multiIndex.value[1]];
  const minute = multiRange.value[2][multiIndex.value[2]];

  return `${dateStr} ${hour} ${minute}`;
});

// 将显示格式转换为标准日期时间格式
const getStandardDateTime = () => {
  if (!multiRange.value.length) return '';
  
  // 解析日期字符串
  const dateStr = multiRange.value[0][multiIndex.value[0]];
  let dateMatch;
  let year, month, day;
  
  // 尝试匹配带年份的格式：2024年1月1日周一
  dateMatch = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
  if (dateMatch) {
    year = dateMatch[1];
    month = String(dateMatch[2]).padStart(2, '0');
    day = String(dateMatch[3]).padStart(2, '0');
  } else {
    // 尝试匹配不带年份的格式：1月1日周一
    dateMatch = dateStr.match(/(\d{1,2})月(\d{1,2})日/);
    if (dateMatch) {
      const currentYear = new Date().getFullYear();
      year = currentYear;
      month = String(dateMatch[1]).padStart(2, '0');
      day = String(dateMatch[2]).padStart(2, '0');
    } else {
      return '';
    }
  }
  
  // 如果是date模式，只返回日期部分
  if (props.mode === 'date') {
    return `${year}/${month}/${day}`;
  }
  
  // 如果是hour模式，只返回日期和小时
  if (props.mode === 'hour') {
    const hourStr = multiRange.value[1][multiIndex.value[1]];
    const hour = hourStr.replace('时', '');
    return `${year}/${month}/${day} ${hour}:00:00`;
  }
  
  // 去掉时分的中文单位
  const hourStr = multiRange.value[1][multiIndex.value[1]];
  const minuteStr = multiRange.value[2][multiIndex.value[2]];
  
  const hour = hourStr.replace('时', '');
  const minute = minuteStr.replace('分', '');

  return `${year}/${month}/${day} ${hour}:${minute}:00`;
}

// 方法
const onMultiChange = (e) => {
  multiIndex.value = e.detail.value;
  emit('update:modelValue', getStandardDateTime());
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    // 处理日期格式，支持 "/" 和 "-" 分隔符
    const dateParts = newValue.split(/[\/\- :]/);
    
    if (dateParts.length >= 3) {
      const year = parseInt(dateParts[0]);
      const month = parseInt(dateParts[1]);
      const day = parseInt(dateParts[2]);
      
      // 构造目标日期字符串
      const targetDate = new Date(year, month - 1, day);
      const weekDay = getWeekDay(targetDate);
      const currentYear = new Date().getFullYear();
      
      // 如果是今年，不显示年份
      let targetDateStr;
      if (year === currentYear) {
        targetDateStr = `${month}月${day}日${weekDay}`;
      } else {
        targetDateStr = `${year}年${month}月${day}日${weekDay}`;
      }
      
      // 在日期列表中查找对应的索引
      const dateRange = multiRange.value[0];
      const dateIndex = dateRange.findIndex(dateStr => dateStr === targetDateStr);
      
      if (dateIndex >= 0) {
        if (props.mode === 'date') {
          multiIndex.value = [dateIndex];
        } else if (props.mode === 'hour' && dateParts.length >= 4) {
          const hour = parseInt(dateParts[3]);
          multiIndex.value = [
            dateIndex,
            hour // 小时索引直接使用数值
          ];
        } else if (props.mode === 'datetime' && dateParts.length >= 5) {
          const hour = parseInt(dateParts[3]);
          const minute = parseInt(dateParts[4]);
          multiIndex.value = [
            dateIndex,
            hour, // 小时索引直接使用数值
            minute // 分钟索引直接使用数值
          ];
        }
      }
    }
  }
}, { immediate: true });

// 监听mode变化，重新生成范围数据
watch(() => props.mode, () => {
  multiRange.value = getMultiRange();
  multiIndex.value = getInitialMultiIndex();
});
</script>

<style scoped>
.picker-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  background: #fafafa;
  min-height: 48rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picker-text.placeholder {
  color: #999;
}

.picker-arrow {
  color: #999;
  font-size: 32rpx;
  margin-left: 16rpx;
}

/* 尝试调整picker内部样式 - 这些可能不会生效，因为picker是系统组件 */
:deep(.uni-picker-container) {
  display: flex;
}

:deep(.uni-picker-item) {
  flex: 1;
  text-align: center;
}

:deep(.uni-picker-item:first-child) {
  flex: 2; /* 尝试让第一列占更多空间 */
  font-size: 24rpx; /* 第一列使用较小字体 */
}

:deep(.uni-picker-item:nth-child(2)) {
  flex: 1;
}

:deep(.uni-picker-item:nth-child(3)) {
  flex: 1;
}

/* 微信小程序特定样式 */
:deep(.picker-col) {
  flex: 1;
  text-align: center;
}

:deep(.picker-col:first-child) {
  flex: 2;
  font-size: 24rpx;
}

/* picker-view相关样式 */
:deep(.picker-view-column) {
  flex: 1;
  text-align: center;
}

:deep(.picker-view-column:first-child) {
  flex: 2;
  font-size: 24rpx;
}

/* 尝试调整picker内部文字样式 */
:deep(.picker-view-column text) {
  font-size: 28rpx;
}

:deep(.picker-view-column:first-child text) {
  font-size: 24rpx;
}
</style>